package org.votes.template;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

public abstract class AbstractTemplateEngine implements TemplateEngine {
	
	public String realPath ;
	
	public String generatorPath;
	
	public abstract String getTemplatePath();

	public abstract String getTemplate();

	public abstract String getEngineType();

	public void run(Map context) throws Exception {
		if (Constants.ENGINE_TYPE_FREEMARKER.equals(getEngineType()))
			executeFreemarker(context);
		else
			executeVelocity(context);
	}
	

	private void executeFreemarker(Map context) throws Exception {
		Configuration cfg = new Configuration();
		
		cfg.setDirectoryForTemplateLoading(new File(getTemplatePath()));
		cfg.setEncoding(Locale.CHINA, "utf-8");  
		cfg.setObjectWrapper(new DefaultObjectWrapper());

		cfg.setCacheStorage(new freemarker.cache.MruCacheStorage(20, 250));

		Template temp = cfg.getTemplate(getTemplate());
		Writer out=new OutputStreamWriter(new FileOutputStream(generatorPath), "UTF-8");  
        temp.process(context, out);  
	}

	private void executeVelocity(Map root) throws Exception {

		Velocity.init();
		VelocityContext context = new VelocityContext(root);
		org.apache.velocity.Template template = null;

		template = Velocity.getTemplate(getTemplatePath() + getTemplate());

		StringWriter sw = new StringWriter();
		template.merge(context, sw);
		System.out.print(sw.toString());

	}
}
